#!/usr/bin/env python
"""
TkTris prealpha-dev-whatever - a simple graphic client for testing
Copyright (c) 2009 Edoardo Spadolini <kerio00@gmail.com>

This thing is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or any
later version.

This thing is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""

from tkinter import *
import tkinter.messagebox as messagebox
import pytris

def callmove(i):
    def wrap():
        move(i)
    return wrap

def move(i):
    buttons[i]["state"] = "disabled"
    buttons[i]["text"] = "X"
    board[i] = 1
    win = pytris.winning(board, i)
    if win == 1:
        messagebox.showerror("WIN", "YOU WIN")
        for btn in buttons:
            btn["state"] = "disabled"
        return
    elif win == 0 and 0 not in board:
        messagebox.showinfo("DRAW", "DRAW GAME")
        for btn in buttons:
            btn["state"] = "disabled"
        return
    elif win == -1:
        messagebox.showinfo("LOSE", "YOU LOSE")
        for btn in buttons:
            btn["state"] = "disabled"
        return

    m = ai_move(board, -1)
    buttons[m]["state"] = "disabled"
    buttons[m]["text"] = "O"
    board[m] = -1
    win = pytris.winning(board, m)
    if win == 1:
        messagebox.showerror("WIN", "YOU WIN")
        for btn in buttons:
            btn["state"] = "disabled"
        return
    elif win == 0 and 0 not in board:
        messagebox.showinfo("DRAW", "DRAW GAME")
        for btn in buttons:
            btn["state"] = "disabled"
        return
    elif win == -1:
        messagebox.showinfo("LOSE", "YOU LOSE")
        for btn in buttons:
            btn["state"] = "disabled"
        return

ai_move = pytris.ai_negamax
  
def newgame():
    for i in range(9):
        board[i] = 0
        buttons[i]["text"] = ""
        buttons[i]["state"] = "normal"

root = Tk()
btnframe = Frame(root)
btnframe.pack(side=TOP, expand=YES, fill=BOTH)
newbtn = Button(root, command=newgame, text="NEW GAME")
newbtn.pack(side=BOTTOM, expand=NO, fill=X)
buttons = [Button(btnframe, text="", width=10, height=4) for i in range(9)]
for i, button in enumerate(buttons):
    button["command"] = callmove(i)
    button.grid(row=i//3, column=i%3, sticky=N+E+W+S)

board = [0] * 9
if 1: # TODO: add switch for this
    m = ai_move(board, -1)
    buttons[m]["state"] = "disabled"
    buttons[m]["text"] = "O"
    board[m] = -1

root.mainloop()
